package com.ricky.core.net.msg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.ricky.core.net.protocol.AMF3;

import flex.messaging.io.amf.Amf3Input;
import flex.messaging.io.amf.Amf3Output;

public class AMF3Context  extends Context<Map>{

	 
	public AMF3Context()
	{
		
	}
	
	public AMF3Context(Map obj)
	{
		super.setContent(obj);
	}

	/* (non-Javadoc)
	 * @see com.ricky.core.net.msg.Context#getBytes()
	 */
	@Override
	public byte[] getBytes() {
		
		if(bytes!=null)
			return bytes;
		if(getContent()!=null)		
		{
			if(amfout==null)
			{
				amfout=new Amf3Output(AMF3.serializationContext);
				byteoutStream=new ByteArrayOutputStream(); 
				dataoutstream=new DataOutputStream(byteoutStream);
			}
			amfout.setOutputStream(dataoutstream);
			try {
				amfout.writeObject(this.getContent());
				amfout.writeObjectEnd();
			} catch (IOException e) {
				 e.printStackTrace();
			}
			bytes=byteoutStream.toByteArray();
			
			return bytes;
		}
		else
			return new byte[0];
	}

	/* (non-Javadoc)
	 * @see com.ricky.core.net.msg.Context#decode(byte[])
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void decode(byte[] in) {
		if(amfin==null)
		{
			amfin=new Amf3Input(AMF3.serializationContext);
		}
		
		byteinStream=new ByteArrayInputStream(in); 
		datainstream=new DataInputStream(byteinStream);		
		amfin.setInputStream(datainstream);
		HashMap<String, ?> obj=null;
		
		try {
			obj = (HashMap<String, ?>) amfin.readObject();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		this.setContent(obj);
		this.setHead(obj.get("cmd").toString());
		obj.remove("cmd");
	}

	//
	private Amf3Output amfout=null;
	private ByteArrayOutputStream byteoutStream=null;   
	private DataOutputStream dataoutstream=null;//   
	private Amf3Input amfin=null;
	private DataInputStream datainstream=null;
	private ByteArrayInputStream byteinStream=null;
	private byte[] bytes=null;
	
}
